package com.jyl.test.genId;

import java.util.UUID;

/**
 * @TODO
 * @author Long
 * @date 2018年7月24日下午4:08:19
 */
public class GenIdUtil {
	
	private static long adjust = 1;
	
	private static long nextId = 0;
	
	private static long lastId = -1;
	
	private static void init() {
		try {
			
			/**
			 * #用于分布式产生主键id,部署到不同的服务器时修改这个值，从1开始(正整数)
				#不同的应用服务器（连接同一数据服务器）需要保证这个数不同，否则必然会产生重复ID。
				genId.adjust=1
			 */
			String strAdjust = "1";
			if (strAdjust != null) {
				adjust = Integer.parseInt(strAdjust);
			}
		} catch (Exception ex) {
			adjust=1;
		}
	}

	private static  void getNextIdBlock() {
		
		init();
		Long bound=-1L;
		Integer incremental=-1;
		String sql="SELECT bound,incremental FROM SYS_DB_ID T WHERE T.ID=?";
		String upSql="UPDATE SYS_DB_ID  SET BOUND=? WHERE ID=?";
		try{
			//Map map = jdbcTemplate.queryForMap(sql, new Object[] { adjust });
			//bound = Long.parseLong(map.get("bound").toString());
			//incremental = Integer.parseInt(map.get("incremental").toString());
			nextId = bound;
			lastId = bound + incremental;
			//jdbcTemplate.update(upSql, new Object[] { lastId , adjust });
		}
		catch(Exception e){
			insertNewComputer();
		}
	}
	
	private static void insertNewComputer(){
		try{
			lastId = 10000;
			String sql="INSERT INTO SYS_DB_ID (id,incremental,bound) VALUES("+adjust+",10000,"+lastId+")";
			//jdbcTemplate.update(sql);
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public static synchronized long genId() {
		if (lastId <= nextId) {
			getNextIdBlock();
		}
		long _nextId = nextId++;
		return _nextId + adjust*10000000000000L;
	}
	
	public static final String getGuid() {
		UUID uuid = UUID.randomUUID();
		return uuid.toString();
	}
	
	public static void main(String[] args) throws Exception {
	
		
	}

}
